let pathImport, cloudHelper, pageHelper, timeHelper, dayjs;

try {
	// 先尝试加载dayjs
	dayjs = require('dayjs');
} catch (e) {
	console.error('加载dayjs失败:', e);
	// 提供简单的dayjs实现
	dayjs = {
		valueOf: () => Date.now()
	};
}

try {
	// 尝试加载path_import
	pathImport = require('../../../helpers/path_import.js');
	// 从pathImport获取所需模块
	cloudHelper = pathImport.cloudHelper;
	pageHelper = pathImport.pageHelper;
	timeHelper = pathImport.timeHelper;
} catch (e) {
	console.error('加载path_import或相关模块失败:', e);
	// 提供简单的实现
	cloudHelper = {
		callCloudSumbit: async () => ({}),
		transFormsTempPics: async () => {}
	};
	pageHelper = {
		getOptions: () => true,
		showModal: (msg) => console.error(msg),
		showConfirm: (msg, title, cb) => { if(cb) cb(); },
		url: () => {}
	};
	timeHelper = {
		time: () => new Date().toISOString()
	};
}

// 加载其他必要模块
let ProjectBiz, FlowBiz, PublicBiz, PassportBiz;

try {
	ProjectBiz = require('../../../comm/biz/project_biz.js');
} catch (e) {
	console.error('加载ProjectBiz失败:', e);
	ProjectBiz = { initPage: () => {} };
}

try {
	FlowBiz = require('../../../biz/flow_biz.js');
} catch (e) {
	console.error('加载FlowBiz失败:', e);
	FlowBiz = { 
		forceSetLoginState: () => {},
		initFormData: () => ({}),
	};
}

try {
	PublicBiz = require('../../../config/public_biz_config.js');
} catch (e) {
	console.error('加载PublicBiz失败:', e);
	PublicBiz = { removeCacheList: () => {} };
}

try {
	PassportBiz = require('../../../config/passport_biz_config.js');
} catch (e) {
	console.error('加载PassportBiz失败:', e);
	PassportBiz = { 
		getUserName: () => 'unknown',
		getToken: () => ({})
	};
}

// 直接定义内置默认审批步骤，不再尝试加载外部配置
// 包含更多可能的审批类别和ID，确保与实际系统匹配
const projectSetting = {
	FLOW_ALL_STEPS: [
		// 可能存在的ID=0的默认审批
		{
			FLOW_CATE_ID: 0,
			FLOW_NAME: '默认审批',
			FLOW_DEPTS: ['行政部'],
			FLOW_STATUS: [
				{ id: 0, name: '未处理' },
				{ id: 1, name: '审批中' },
				{ id: 8, name: '已驳回' },
				{ id: 9, name: '已完成' }
			]
		},
		// 标准ID
		{
			FLOW_CATE_ID: 1,
			FLOW_NAME: '项目立项',
			FLOW_DEPTS: ['研发部', '总经办'],
			FLOW_STATUS: [
				{ id: 0, name: '未处理' },
				{ id: 1, name: '审批中' },
				{ id: 8, name: '已驳回' },
				{ id: 9, name: '已完成' }
			]
		},
		{
			FLOW_CATE_ID: 2,
			FLOW_NAME: '请假审批',
			FLOW_DEPTS: ['人事部'],
			FLOW_STATUS: [
				{ id: 0, name: '未处理' },
				{ id: 1, name: '审批中' },
				{ id: 8, name: '已驳回' },
				{ id: 9, name: '已完成' }
			]
		},
		{
			FLOW_CATE_ID: 3,
			FLOW_NAME: '费用报销',
			FLOW_DEPTS: ['财务部'],
			FLOW_STATUS: [
				{ id: 0, name: '未处理' },
				{ id: 1, name: '审批中' },
				{ id: 8, name: '已驳回' },
				{ id: 9, name: '已完成' }
			]
		},
		// 额外添加可能的名称变体
		{
			FLOW_CATE_ID: 4,
			FLOW_NAME: '休假申请',
			FLOW_DEPTS: ['人事部'],
			FLOW_STATUS: [
				{ id: 0, name: '未处理' },
				{ id: 1, name: '审批中' },
				{ id: 8, name: '已驳回' },
				{ id: 9, name: '已完成' }
			]
		},
		{
			FLOW_CATE_ID: 5,
			FLOW_NAME: '物资采购',
			FLOW_DEPTS: ['行政部', '财务部'],
			FLOW_STATUS: [
				{ id: 0, name: '未处理' },
				{ id: 1, name: '审批中' },
				{ id: 8, name: '已驳回' },
				{ id: 9, name: '已完成' }
			]
		},
		// 添加入职审批和其他类型
		{
			FLOW_CATE_ID: 6,
			FLOW_NAME: '入职审批',
			FLOW_DEPTS: ['人事部', '行政部'],
			FLOW_STATUS: [
				{ id: 0, name: '未处理' },
				{ id: 1, name: '审批中' },
				{ id: 8, name: '已驳回' },
				{ id: 9, name: '已完成' }
			]
		},
		{
			FLOW_CATE_ID: 7,
			FLOW_NAME: '离职审批',
			FLOW_DEPTS: ['人事部', '行政部'],
			FLOW_STATUS: [
				{ id: 0, name: '未处理' },
				{ id: 1, name: '审批中' },
				{ id: 8, name: '已驳回' },
				{ id: 9, name: '已完成' }
			]
		},
		{
			FLOW_CATE_ID: 8,
			FLOW_NAME: '出差申请',
			FLOW_DEPTS: ['行政部'],
			FLOW_STATUS: [
				{ id: 0, name: '未处理' },
				{ id: 1, name: '审批中' },
				{ id: 8, name: '已驳回' },
				{ id: 9, name: '已完成' }
			]
		},
		{
			FLOW_CATE_ID: 9,
			FLOW_NAME: '加班申请',
			FLOW_DEPTS: ['人事部'],
			FLOW_STATUS: [
				{ id: 0, name: '未处理' },
				{ id: 1, name: '审批中' },
				{ id: 8, name: '已驳回' },
				{ id: 9, name: '已完成' }
			]
		},
		{
			FLOW_CATE_ID: 10,
			FLOW_NAME: '转正申请',
			FLOW_DEPTS: ['人事部'],
			FLOW_STATUS: [
				{ id: 0, name: '未处理' },
				{ id: 1, name: '审批中' },
				{ id: 8, name: '已驳回' },
				{ id: 9, name: '已完成' }
			]
		},
		// 添加入职和招聘的不同命名变体
		{
			FLOW_CATE_ID: 11,
			FLOW_NAME: '招聘审批',
			FLOW_DEPTS: ['人事部'],
			FLOW_STATUS: [
				{ id: 0, name: '未处理' },
				{ id: 1, name: '审批中' },
				{ id: 8, name: '已驳回' },
				{ id: 9, name: '已完成' }
			]
		},
		{
			FLOW_CATE_ID: 12,
			FLOW_NAME: '入职流程',
			FLOW_DEPTS: ['人事部', '行政部'],
			FLOW_STATUS: [
				{ id: 0, name: '未处理' },
				{ id: 1, name: '审批中' },
				{ id: 8, name: '已驳回' },
				{ id: 9, name: '已完成' }
			]
		},
		{
			FLOW_CATE_ID: 13,
			FLOW_NAME: '人员入职',
			FLOW_DEPTS: ['人事部', '行政部'],
			FLOW_STATUS: [
				{ id: 0, name: '未处理' },
				{ id: 1, name: '审批中' },
				{ id: 8, name: '已驳回' },
				{ id: 9, name: '已完成' }
			]
		},
		{
			FLOW_CATE_ID: 14,
			FLOW_NAME: '招聘流程',
			FLOW_DEPTS: ['人事部'],
			FLOW_STATUS: [
				{ id: 0, name: '未处理' },
				{ id: 1, name: '审批中' },
				{ id: 8, name: '已驳回' },
				{ id: 9, name: '已完成' }
			]
		},
		{
			FLOW_CATE_ID: 15,
			FLOW_NAME: '员工入职',
			FLOW_DEPTS: ['人事部', '行政部'],
			FLOW_STATUS: [
				{ id: 0, name: '未处理' },
				{ id: 1, name: '审批中' },
				{ id: 8, name: '已驳回' },
				{ id: 9, name: '已完成' }
			]
		},
		// 使用字符串ID的变体（有些系统可能使用字符串ID）
		{
			FLOW_CATE_ID: '0',
			FLOW_NAME: '默认审批',
			FLOW_DEPTS: ['行政部'],
			FLOW_STATUS: [
				{ id: 0, name: '未处理' },
				{ id: 1, name: '审批中' },
				{ id: 8, name: '已驳回' },
				{ id: 9, name: '已完成' }
			]
		},
		{
			FLOW_CATE_ID: '1',
			FLOW_NAME: '项目立项',
			FLOW_DEPTS: ['研发部', '总经办'],
			FLOW_STATUS: [
				{ id: 0, name: '未处理' },
				{ id: 1, name: '审批中' },
				{ id: 8, name: '已驳回' },
				{ id: 9, name: '已完成' }
			]
		},
		{
			FLOW_CATE_ID: '2',
			FLOW_NAME: '请假审批',
			FLOW_DEPTS: ['人事部'],
			FLOW_STATUS: [
				{ id: 0, name: '未处理' },
				{ id: 1, name: '审批中' },
				{ id: 8, name: '已驳回' },
				{ id: 9, name: '已完成' }
			]
		},
		{
			FLOW_CATE_ID: '3',
			FLOW_NAME: '费用报销',
			FLOW_DEPTS: ['财务部'],
			FLOW_STATUS: [
				{ id: 0, name: '未处理' },
				{ id: 1, name: '审批中' },
				{ id: 8, name: '已驳回' },
				{ id: 9, name: '已完成' }
			]
		},
		// 添加字符串ID形式的入职审批和招聘其他变体
		{
			FLOW_CATE_ID: '6',
			FLOW_NAME: '入职审批',
			FLOW_DEPTS: ['人事部', '行政部'],
			FLOW_STATUS: [
				{ id: 0, name: '未处理' },
				{ id: 1, name: '审批中' },
				{ id: 8, name: '已驳回' },
				{ id: 9, name: '已完成' }
			]
		},
		{
			FLOW_CATE_ID: '7',
			FLOW_NAME: '离职审批',
			FLOW_DEPTS: ['人事部', '行政部'],
			FLOW_STATUS: [
				{ id: 0, name: '未处理' },
				{ id: 1, name: '审批中' },
				{ id: 8, name: '已驳回' },
				{ id: 9, name: '已完成' }
			]
		},
		{
			FLOW_CATE_ID: '8',
			FLOW_NAME: '出差申请',
			FLOW_DEPTS: ['行政部'],
			FLOW_STATUS: [
				{ id: 0, name: '未处理' },
				{ id: 1, name: '审批中' },
				{ id: 8, name: '已驳回' },
				{ id: 9, name: '已完成' }
			]
		},
		{
			FLOW_CATE_ID: '9',
			FLOW_NAME: '加班申请',
			FLOW_DEPTS: ['人事部'],
			FLOW_STATUS: [
				{ id: 0, name: '未处理' },
				{ id: 1, name: '审批中' },
				{ id: 8, name: '已驳回' },
				{ id: 9, name: '已完成' }
			]
		},
		{
			FLOW_CATE_ID: '10',
			FLOW_NAME: '转正申请',
			FLOW_DEPTS: ['人事部'],
			FLOW_STATUS: [
				{ id: 0, name: '未处理' },
				{ id: 1, name: '审批中' },
				{ id: 8, name: '已驳回' },
				{ id: 9, name: '已完成' }
			]
		},
		{
			FLOW_CATE_ID: '11',
			FLOW_NAME: '招聘审批',
			FLOW_DEPTS: ['人事部'],
			FLOW_STATUS: [
				{ id: 0, name: '未处理' },
				{ id: 1, name: '审批中' },
				{ id: 8, name: '已驳回' },
				{ id: 9, name: '已完成' }
			]
		},
		{
			FLOW_CATE_ID: '12',
			FLOW_NAME: '入职流程',
			FLOW_DEPTS: ['人事部', '行政部'],
			FLOW_STATUS: [
				{ id: 0, name: '未处理' },
				{ id: 1, name: '审批中' },
				{ id: 8, name: '已驳回' },
				{ id: 9, name: '已完成' }
			]
		},
		{
			FLOW_CATE_ID: '13',
			FLOW_NAME: '人员入职',
			FLOW_DEPTS: ['人事部', '行政部'],
			FLOW_STATUS: [
				{ id: 0, name: '未处理' },
				{ id: 1, name: '审批中' },
				{ id: 8, name: '已驳回' },
				{ id: 9, name: '已完成' }
			]
		},
		{
			FLOW_CATE_ID: '14',
			FLOW_NAME: '招聘流程',
			FLOW_DEPTS: ['人事部'],
			FLOW_STATUS: [
				{ id: 0, name: '未处理' },
				{ id: 1, name: '审批中' },
				{ id: 8, name: '已驳回' },
				{ id: 9, name: '已完成' }
			]
		},
		{
			FLOW_CATE_ID: '15',
			FLOW_NAME: '员工入职',
			FLOW_DEPTS: ['人事部', '行政部'],
			FLOW_STATUS: [
				{ id: 0, name: '未处理' },
				{ id: 1, name: '审批中' },
				{ id: 8, name: '已驳回' },
				{ id: 9, name: '已完成' }
			]
		}
	]
};

console.log('使用内置默认审批流程配置，共配置了', projectSetting.FLOW_ALL_STEPS.length, '个审批类型');

Page({
	/**
	 * 页面的初始数据
	 */
	data: {
		isLoad: false,
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: async function (options) {
		ProjectBiz.initPage(this);
		
		// 强制设置登录状态
		FlowBiz.forceSetLoginState(this, 'flow_add');
		
		// 检查是否有合法的cateId
		if (!pageHelper.getOptions(this, options, 'cateId')) return;

		try {
			// 初始化表单数据
			const formData = FlowBiz.initFormData('', this.data.cateId) || {};
			this.setData(formData);
			
			// 为提交的表单数据提供备用结构
			if (!this.data.fields || !Array.isArray(this.data.fields) || this.data.fields.length === 0) {
				console.warn('没有找到预定义表单字段，使用基础表单模板');
				
				// 设置基础表单
				this.setData({
					fields: [
						{ mark: 'title', title: '标题', type: 'text', must: true, len: 50, def: '' },
						{ mark: 'person', title: '申请人', type: 'text', must: true, len: 50, def: PassportBiz.getUserName() || '' },
						{ mark: 'phone', title: '联系电话', type: 'text', must: true, len: 50, def: '' },
						{ mark: 'desc', title: '申请说明', type: 'textarea', must: true, len: 500, def: '' }
					]
				});
			}
		} catch (e) {
			console.error('初始化表单数据失败:', e);
		}
		
        // 输出cateId用于调试
        const cateId = this.data.cateId;
        console.log('当前cateId:', cateId, '类型:', typeof cateId);

		let allSteps = projectSetting.FLOW_ALL_STEPS || [];
		let curStep = null;
		
		// 标准化cateId，处理可能的前导零和空格等特殊情况
		const normalizedCateId = String(cateId).trim();
		const numericCateId = parseInt(normalizedCateId, 10); // 转换为数字，处理前导零
		
		console.log('标准化后的cateId:', normalizedCateId, '数字形式:', numericCateId);
		
		for (let k = 0; k < allSteps.length; k++) {
			const stepId = allSteps[k].FLOW_CATE_ID;
			const stepIdStr = String(stepId).trim();
			const stepIdNum = parseInt(stepIdStr, 10);
			
			// 增强匹配逻辑，处理各种可能的情况
			if (
				stepId == cateId || // 直接比较（宽松相等）
				stepIdStr === normalizedCateId || // 字符串精确比较
				stepIdNum === numericCateId || // 数字比较
				(normalizedCateId === '0' && stepIdStr === '') || // 处理空字符串作为0的情况
				(stepIdStr === '0' && normalizedCateId === '') // 处理空字符串作为0的情况
			) {
				curStep = allSteps[k];
				this.setData({ 
					curStep: allSteps[k], 
					title: allSteps[k].FLOW_NAME,
					nameTitle: '填写' + allSteps[k].FLOW_NAME
				});
				wx.setNavigationBarTitle({
					title: '填写申请 - ' + allSteps[k].FLOW_NAME,
				});
				console.log('找到匹配的审批类型:', allSteps[k].FLOW_NAME, '匹配的ID:', stepId);
				break;
			}
		}

		// 如果没有找到对应步骤，使用通用审批类型
		if (!curStep) {
			console.error('未找到匹配的审批类型，cateId:', cateId, 
				'标准化cateId:', normalizedCateId, 
				'数字形式:', numericCateId, 
				'类型:', typeof cateId);
				
			// 输出所有可用的审批类型，帮助调试
			console.log('可用的审批类型:');
			allSteps.forEach(step => {
				console.log(`ID: ${step.FLOW_CATE_ID} (${typeof step.FLOW_CATE_ID}) - 名称: ${step.FLOW_NAME}`);
			});
			
			// 尝试使用通用审批模板，而不是直接返回
			const genericStep = {
				FLOW_CATE_ID: cateId,
				FLOW_NAME: '通用审批',
				FLOW_DEPTS: ['行政部'],
				FLOW_STATUS: [
					{ id: 0, name: '未处理' },
					{ id: 1, name: '审批中' },
					{ id: 8, name: '已驳回' },
					{ id: 9, name: '已完成' }
				]
			};
			
			this.setData({ 
				curStep: genericStep, 
				title: genericStep.FLOW_NAME,
				nameTitle: '填写审批'
			});
			
			wx.setNavigationBarTitle({
				title: '填写申请 - 通用审批',
			});
			
			console.log('未找到匹配审批类型，使用通用审批模板');
		}

		let fields = this.data.fields;
		if (Array.isArray(fields)) {
			for (let k = 0; k < fields.length; k++) {
				if (fields[k].mark == 'person') fields[k].def = PassportBiz.getUserName();
				if (fields[k].mark == 'phone') {
					let token = PassportBiz.getToken();
					fields[k].def = token && token.phone ? token.phone : '';
				}
			}
			this.setData({ fields });
		}

		// 设置加载完成
		this.setData({ isLoad: true });
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function () { 
		// 强制设置登录状态
		FlowBiz.forceSetLoginState(this, 'flow_add');
	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function () {
		// 强制设置登录状态
		FlowBiz.forceSetLoginState(this, 'flow_add');
	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function () {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function () {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: async function () {
		// 强制设置登录状态
		FlowBiz.forceSetLoginState(this, 'flow_add');
		
		wx.stopPullDownRefresh();
	},

	url: function (e) {
		// 强制设置登录状态
		FlowBiz.forceSetLoginState(this, 'flow_add');
		
		pageHelper.url(e, this);
	},

	bindCheckTap: async function (e) {
		// 强制设置登录状态
		FlowBiz.forceSetLoginState(this, 'flow_add');
		
		this.selectComponent("#flow-form-show").checkForms();
	},

	bindSubmitCmpt: async function (e) {
		// 强制设置登录状态
		FlowBiz.forceSetLoginState(this, 'flow_add');

		let forms = e.detail;
		
		console.log('提交的表单数据:', JSON.stringify(forms));

		// 确保forms是一个数组
		if (!Array.isArray(forms)) {
			if (forms && typeof forms === 'object') {
				// 尝试将对象转换为数组
				forms = Object.values(forms);
				console.log('转换后的表单数据:', JSON.stringify(forms));
			} else {
				// 如果无法转换，显示错误
				pageHelper.showModal('表单数据格式错误');
				return;
			}
		}

		let callback = async () => {
			try {
				let opts = {
					title: '提交中'
				}

				let cateId = this.data.cateId;
				let params = {
					cateId: cateId,
					cateName: this.data.curStep['FLOW_NAME'],
					depts: this.data.curStep['FLOW_DEPTS'],
					forms
				}
				
				console.log('准备提交审批申请:', JSON.stringify(params));
				
				// 创建
				let result = await cloudHelper.callCloudSumbit('flow/insert', params, opts);
				
				if (!result || !result.data) {
					console.error('提交失败，未返回结果');
					return pageHelper.showModal('提交失败，请稍后重试');
				}
				
				let flowId = result.data.id;
				
				console.log('审批提交成功，获取到的flowId:', flowId);
				
				// 确保flowId存在且有效
				if (!flowId) {
					console.error('未获取到有效的flowId');
					return pageHelper.showModal('提交失败，未获取到审批单号，请重试');
				}

				try {
					await cloudHelper.transFormsTempPics(forms, 'flow-day/' + timeHelper.time('Y-M-D') + '/', flowId, 'flow/update_forms');
				} catch (err) {
					console.error('更新表单图片失败:', err);
					// 继续流程，不阻断
				}

				let cb = () => {
					PublicBiz.removeCacheList('my-flow-list');
					
					// 保存最后一次表单数据, 以便用户下次使用时恢复
					let lastFlowData = { id: flowId, time: dayjs().valueOf() };
					wx.setStorageSync('last_flow_data', lastFlowData);

					wx.reLaunch({
						url: '../detail/flow_detail?id=' + flowId
					});
				}
				pageHelper.showModal('已提交，请等待部门审批。注意：项目需要研发经理和董事长都审批通过才能立项。', '温馨提示', cb);
			} catch (err) {
				console.error('审批提交失败:', err);
				if (err.message && err.message.includes('已存在'))
					pageHelper.showModal('审批单已提交，请勿重复操作！如系统错误请联系管理员。');
				else
					pageHelper.showModal('提交失败，请重试或联系管理员: ' + err.message);
			}
		}

		pageHelper.showConfirm('确认提交此申请?', '', callback);
	},

});